<template>
  <view class="custom-tabbar" :style="{ zIndex: zIndex }">
    <view class="tabbar-container">
      <view v-for="(item, index) in dynamicTabBarList" :key="index" class="tabbar-item"
        :class="{ active: currentPath === item.pagePath, loading: loadingTab === item.pagePath }" @click="switchTab(item)"
        :style="{ width: `${itemWidth}%`, '--primary-color-ripple': themeColorStyles.primaryColorRipple }">
        <view class="tabbar-icon">
          <image v-if="currentPath === item.pagePath" :src="item.selectedIconPath" class="icon-image selected"
            mode="aspectFit" />
          <image v-else :src="item.iconPath" class="icon-image" mode="aspectFit" />
          <!-- 加载状态指示器 -->
          <view class="loading-indicator" v-if="loadingTab === item.pagePath">
            <view class="loading-dot" :style="{background: `linear-gradient(45deg, ${themeColorStyles.primaryColor}, ${themeColorStyles.primaryColorGlow})`}"></view>
          </view>
          <!-- 购物车角标 -->
          <view v-if="item.pagePath === 'pages/cart/index' && cartCount > 0" class="cart-badge" 
                :style="{background: `linear-gradient(135deg, ${themeColorStyles.primaryColor}, ${themeColorStyles.primaryColor}dd)`}">
            <text class="badge-text">{{ cartCount > 99 ? '99+' : cartCount }}</text>
          </view>
        </view>
        <text class="tabbar-text" :class="{ 'active': currentPath === item.pagePath }"
          :style="{ color: currentPath === item.pagePath ? themeColorStyles.primaryColor : normalColor }">
          {{ item.text }}
        </text>
      </view>
    </view>
    <!-- 安全区域适配 -->
    <view class="safe-area-bottom"></view>
  </view>
</template>

<script>
import { getTabBarIconPath, getThemeColorFromGlobal, getThemePrimaryColor } from '@/utils/themeUtils'

export default {
  name: 'CustomTabbar',
  props: {
    currentPath: {
      type: String,
      default: 'pages/index'
    },
    zIndex: {
      type: Number,
      default: 1000
    },
    normalColor: {
      type: String,
      default: '#999999'
    },
    selectedColor: {
      type: String,
      default: '#007AFF'
    }
  },
  data() {
    return {
      cartCount: 0,
      loadingTab: '', // 当前加载中的tab
      rippleEffect: false, // 波纹效果
      themeColor: '1', // 当前主题色
      tabBarList: [
        {
          pagePath: 'pages/index',
          iconName: 'home',
          text: '首页'
        },
        {
          pagePath: 'pages/shop/index',
          iconName: 'shop',
          text: '商品栏'
        },
        {
          pagePath: 'pages/cart/index',
          iconName: 'cart',
          text: '购物车'
        },
        {
          pagePath: 'pages/mine/index',
          iconName: 'mine',
          text: '我的'
        }
      ]
    }
  },
  computed: {
    itemWidth() {
      return 100 / this.tabBarList.length
    },
    // 动态计算TabBar列表，包含图标路径
    dynamicTabBarList() {
      return this.tabBarList.map(item => ({
        ...item,
        iconPath: getTabBarIconPath(this.themeColor, item.iconName, false),
        selectedIconPath: getTabBarIconPath(this.themeColor, item.iconName, true)
      }))
    },
    // 动态主题色样式（用于小程序环境）
    themeColorStyles() {
      const primaryColor = getThemePrimaryColor(this.themeColor)
      const rgb = this.hexToRgb(primaryColor)
      if (!rgb) return {}
      
      return {
        primaryColorGlow: `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.3)`,
        primaryColorRipple: `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.2)`,
        primaryColor: primaryColor
      }
    }
  },
  async mounted() {
    // 隐藏原生TabBar
    uni.hideTabBar()
    // 初始化主题色
    await this.initThemeColor()
    // 获取购物车数量
    this.getCartCount()
    // 监听购物车数量变化
    uni.$on('updateCartCount', this.updateCartCount)
  },
  beforeDestroy() {
    uni.$off('updateCartCount', this.updateCartCount)
  },
  methods: {
    // 初始化主题色
    async initThemeColor() {
      this.themeColor = await getThemeColorFromGlobal()
      console.log('TabBar当前主题色:', this.themeColor)
      this.setThemeColorVariables()
    },
    
    // 设置主题色CSS变量
    setThemeColorVariables() {
      const primaryColor = getThemePrimaryColor(this.themeColor)
      // 将十六进制颜色转换为RGB值
      const rgb = this.hexToRgb(primaryColor)
      if (rgb) {
        // 在小程序环境中，使用uni.setStorageSync存储主题色变量
        // #ifdef MP
        uni.setStorageSync('tabbarThemeColorVariables', {
          '--primary-color': primaryColor,
          '--primary-color-glow': `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.3)`,
          '--primary-color-ripple': `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.2)`
        })
        // #endif
        
        // 在H5环境中，设置CSS变量
        // #ifdef H5
        if (typeof document !== 'undefined' && document.documentElement) {
          const style = document.documentElement.style
          style.setProperty('--primary-color', primaryColor)
          style.setProperty('--primary-color-glow', `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.3)`)
          style.setProperty('--primary-color-ripple', `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.2)`)
        }
        // #endif
      }
    },
    
    // 十六进制颜色转RGB
    hexToRgb(hex) {
      const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
      return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
      } : null
    },
    switchTab(item) {
      console.log('TabBar点击:', item.text, '路径:', item.pagePath)

      // 触发波纹效果
      this.triggerRipple()

      if (this.currentPath !== item.pagePath) {
        // 设置加载状态
        this.loadingTab = item.pagePath

        // 移除震动反馈效果

        uni.switchTab({
          url: `/${item.pagePath}`,
          success: (res) => {
            console.log('跳转成功到:', item.pagePath)
            // 清除加载状态
            setTimeout(() => {
              this.loadingTab = ''
            }, 300)
          },
          fail: (err) => {
            console.error('跳转失败:', err)
            // 清除加载状态
            this.loadingTab = ''
            // 显示错误提示
            uni.showToast({
              title: '页面跳转失败',
              icon: 'none'
            })
          }
        })
      } else {
        // 如果已在当前页面，添加一个小的反馈动画
        this.triggerBounce()
      }
    },

    // 触发波纹效果
    triggerRipple() {
      this.rippleEffect = true
      setTimeout(() => {
        this.rippleEffect = false
      }, 600)
    },

    // 触发弹跳效果（小程序兼容版本）
    triggerBounce() {
      // 在小程序环境中，直接跳过DOM操作
      // #ifdef H5
      try {
        const activeItem = document.querySelector('.tabbar-item.active')
        if (activeItem) {
          activeItem.classList.add('bounce')
          setTimeout(() => {
            activeItem.classList.remove('bounce')
          }, 400)
        }
      } catch (error) {
        console.log('弹跳效果在当前环境不可用')
      }
      // #endif
    },

    // 获取购物车数量
    getCartCount() {
      try {
        const cartData = uni.getStorageSync('cartData')
        if (cartData && Array.isArray(cartData)) {
          this.cartCount = cartData.reduce((total, item) => total + (item.quantity || 0), 0)
        } else {
          this.cartCount = 0
        }
      } catch (error) {
        console.error('获取购物车数量失败:', error)
        this.cartCount = 0
      }
    },

    // 更新购物车数量
    updateCartCount(count) {
      this.cartCount = count || 0
    }
  }
}
</script>

<style lang="scss" scoped>
.custom-tabbar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(180deg, rgba(255, 255, 255, 0.95) 0%, rgba(255, 255, 255, 1) 100%);
  backdrop-filter: blur(20rpx);
  -webkit-backdrop-filter: blur(20rpx);
  box-shadow: 0 -2rpx 20rpx rgba(0, 0, 0, 0.1), 0 -1rpx 0 rgba(255, 255, 255, 0.8) inset;
  border-top: 1rpx solid rgba(0, 0, 0, 0.05);
  z-index: 9999;
  pointer-events: auto;
  overflow: hidden;

  // 移除上方泛光效果，避免影响视野
}

.tabbar-container {
  display: flex;
  align-items: center;
  justify-content: space-around;
  padding: 6rpx 0 4rpx;
  min-height: 80rpx;
}

.tabbar-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  position: relative;
  padding: 8rpx 0 12rpx 0;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  cursor: pointer;
  pointer-events: auto;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    width: 0;
    height: 0;
    background: radial-gradient(circle, var(--primary-color-ripple, rgba(0, 122, 255, 0.2)) 0%, transparent 70%);
    border-radius: 50%;
    transform: translate(-50%, -50%);
    transition: all 0.3s ease;
    pointer-events: none;
  }

  &:active {
    transform: scale(0.92);
    outline: none;
    -webkit-tap-highlight-color: transparent;

    &::before {
      width: 120rpx;
      height: 120rpx;
      animation: ripple 0.6s ease-out;
    }
  }

  &:hover {
    background-color: transparent;
  }

  &:focus {
    outline: none;
  }

  /* 移除移动端点击时的灰色高亮 */
  -webkit-tap-highlight-color: transparent;
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;

  &.active {
    .tabbar-icon {
      transform: translateY(-2rpx);
    }

    .icon-image {
      transform: scale(1.15);
    }

    .tabbar-text {
      transform: scale(1.05);
    }
  }

  &.loading {
      .tabbar-icon {
        animation: pulse 1.5s ease-in-out infinite;
      }

      .icon-image {
        animation: gentle-swing 0.8s ease-in-out infinite;
      }
    }

  &.bounce {
    animation: bounce-feedback 0.4s ease-out;
  }

  // 悬停效果增强
  &:hover:not(.active) {
    .icon-image {
      transform: scale(1.05) translateY(-1rpx);
    }

    .tabbar-text {
      transform: translateY(-1rpx);
    }
  }
}

.tabbar-icon {
  position: relative;
  margin-bottom: 4rpx;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

  .tabbar-item:hover & {
    transform: translateY(-2rpx);
  }
}

.icon-image {
  width: 44rpx;
  height: 44rpx;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

  &.selected {
    transform: scale(1.1);
  }
}

.cart-badge {
  position: absolute;
  top: -8rpx;
  right: -8rpx;
  color: white;
  font-size: 18rpx;
  font-weight: bold;
  padding: 2rpx 6rpx;
  border-radius: 20rpx;
  min-width: 28rpx;
  height: 28rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2rpx solid #ffffff;
  z-index: 10;
  animation: badge-pulse 2s ease-in-out infinite;
  transform-origin: center;
}

.badge-text {
  color: #ffffff;
  font-size: 20rpx;
  font-weight: bold;
  line-height: 1;
  padding: 0 6rpx;
}

.tabbar-text {
  font-size: 20rpx;
  font-weight: 400;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  color: #999999;

  &.active {
    font-weight: 500;
    transform: scale(1.05);
  }
}

.safe-area-bottom {
  height: constant(safe-area-inset-bottom);
  height: env(safe-area-inset-bottom);
  background: inherit;
}

/* 响应式设计 */
@media screen and (max-width: 750rpx) {
  .tabbar-item {
    padding: 6rpx 0 10rpx 0;

    &::before {
      width: 100rpx;
      height: 100rpx;
    }
  }

  .icon-image {
    width: 40rpx;
    height: 40rpx;

    &.selected {
      transform: scale(1.1);
    }
  }

  .tabbar-text {
    font-size: 18rpx;

    &.active {
      transform: scale(1.03);
    }
  }

  .loading-indicator {
    width: 6rpx;
    height: 6rpx;
    top: -2rpx;
  }

  .cart-badge {
    min-width: 24rpx;
    height: 24rpx;
    font-size: 16rpx;
    top: -6rpx;
    right: -6rpx;
  }
}

.cart-badge {
  min-width: 28rpx;
  height: 28rpx;
}

.badge-text {
  font-size: 18rpx;
}

/* 加载指示器样式 */
.loading-indicator {
  position: absolute;
  top: -4rpx;
  left: 50%;
  transform: translateX(-50%);
  width: 8rpx;
  height: 8rpx;
}

.loading-dot {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  animation: loading-bounce 1.4s ease-in-out infinite both;
}

/* 动画定义 */
@keyframes pulse {

  0%,
  100% {
    transform: scale(1);
  }

  50% {
    transform: scale(1.05);
  }
}

@keyframes loading-bounce {

  0%,
  80%,
  100% {
    transform: scale(0);
    opacity: 0.5;
  }

  40% {
    transform: scale(1);
    opacity: 1;
  }
}

/* 温和摆动动画 */
@keyframes gentle-swing {
  0%, 100% {
    transform: rotate(0deg);
  }
  25% {
    transform: rotate(-8deg);
  }
  75% {
    transform: rotate(8deg);
  }
}

@keyframes bounce-feedback {

  0%,
  20%,
  53%,
  80%,
  100% {
    transform: translate3d(0, 0, 0);
  }

  40%,
  43% {
    transform: translate3d(0, -8rpx, 0);
  }

  70% {
    transform: translate3d(0, -4rpx, 0);
  }

  90% {
    transform: translate3d(0, -2rpx, 0);
  }
}

@keyframes ripple {
  0% {
    transform: scale(0);
    opacity: 1;
  }

  100% {
    transform: scale(4);
    opacity: 0;
  }
}

@keyframes badge-pulse {

  0%,
  100% {
    transform: scale(1);
  }

  50% {
    transform: scale(1.1);
  }
}



/* 暗色主题适配 - 暂时注释掉，以后可能会用到 */
/*
@media (prefers-color-scheme: dark) {
  .custom-tabbar {
    background: linear-gradient(180deg, rgba(0, 0, 0, 0.95) 0%, rgba(0, 0, 0, 1) 100%);
    backdrop-filter: blur(20rpx);
    border-top: 1rpx solid rgba(255, 255, 255, 0.1);
    box-shadow: 0 -2rpx 20rpx rgba(0, 0, 0, 0.3), 0 -1rpx 0 rgba(255, 255, 255, 0.1) inset;

    &::before {
      background: linear-gradient(90deg, transparent, rgba(0, 122, 255, 0.5), transparent);
    }
  }

  .tabbar-item {
    &::before {
      background: radial-gradient(circle, rgba(0, 122, 255, 0.3) 0%, transparent 70%);
    }

    &:hover {
      background-color: transparent;
    }

    &.active {
      .icon-image {
      }

      .tabbar-text {
      }
    }
  }

  .tabbar-text {
    color: rgba(255, 255, 255, 0.7);

    &.active {
      color: #007AFF !important;
    }
  }

  .loading-dot {
    background: linear-gradient(45deg, #007AFF, #00D4FF);
  }
}
*/
</style>